package cn.taketoday.live.component;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

import cn.taketoday.live.http.HttpOtherData;

@Component
public class ServerAddressComponent implements ApplicationListener<WebServerInitializedEvent> {
  private int serverPort;

  public int getPort() {
    return this.serverPort;
  }

  public String getAddress() {
    InetAddress address = null;
    String addressStr = "";
    try {
      address = InetAddress.getLocalHost();
      addressStr = address.getHostAddress();
    }
    catch (UnknownHostException e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
      addressStr = "获取失败";
    }
    return "http://" + addressStr + ":" + this.serverPort;
  }

  /**
   * @return
   */
  public String getRemoteAddress() {
    return "http://" + HttpOtherData.httpGetIp() + ":" + this.serverPort;
  }

  @Override
  public void onApplicationEvent(WebServerInitializedEvent event) {
    // TODO 自动生成的方法存根
    this.serverPort = event.getWebServer().getPort();
  }

}
